<?php


class Ext_Image_Download
{
    protected $_url;

    protected $_messager;
    const DOWNLOAD_IMAGE_FAILED = 'downloadImageFailed';
    const WRITE_IMAGE_FAILED    = 'writeImageFailed';
    protected $_messageTemplates = array(
        self::DOWNLOAD_IMAGE_FAILED  => "Download image failed.",
        self::WRITE_IMAGE_FAILED     => "Write image failed.",
    );
    
    public function __construct($url)
    {
        $this->_url = $url;
        
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function download()
    {
        $result = array(
            'code'        => Ext_Image_Download_Result::FAILURE,
            'data'        => '',
            'messages'    => array(),
        );

        $config = Ext_Config::getInstance()->getConfig('image');
        
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        
        $tmpPath = rtrim($config->graphics->tmp, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . 'download' . DIRECTORY_SEPARATOR;
        $tmpFile = $tmpPath.time().'_'.$userId.'_'.Ext_Utility_String::random(6);

        $client = new Zend_Http_Client();
        $client->setUri($this->_url);
        $client->setConfig(array(
            'maxredirects' => 0,
            'timeout'      => 30));
        $response = $client->request();
        
        if(!$response->isSuccessful()){
            $result['messages'][] = $this->_messager->addMessage(self::DOWNLOAD_IMAGE_FAILED);
            return new Ext_Image_Download_Result($result['code'], $result['data'], $result['messages']);
        }

        $writeFileResult = Ext_Utility_File::writeFile($tmpFile, $response->getBody());
        if(!$writeFileResult){
            $result['messages'][] = $this->_messager->addMessage(self::WRITE_IMAGE_FAILED);
            return new Ext_Image_Download_Result($result['code'], $result['data'], $result['messages']);
        }

        $result['code'] = Ext_Image_Download_Result::SUCCESS;
        $result['data'] = $tmpFile;
        return new Ext_Image_Download_Result($result['code'], $result['data'], $result['messages']);
    }
    
}
